package org.adorsys.aderp.orga.service;

import java.util.List;

import org.adorsys.aderp.orga.domain.EmailAddressRole;
import org.adorsys.aderp.orga.domain.OrgaPerson;
import org.adorsys.aderp.orga.domain.PersonEmail;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;


public class PersonEmailServiceImpl implements PersonEmailService {
	
	@Override
	public List<PersonEmail> findByOrgaPerson(OrgaPerson orgaPerson) {
		return personEmailRepository.findByOrgaPerson(orgaPerson);
	}
	
    public void savePersonEmail(PersonEmail personEmail) {
    	OrgaPerson orgaPerson = personEmail.getOrgaPerson();
    	if(StringUtils.isBlank(personEmail.getPersonAddressKey())){
    		EmailAddressRole addressRole = personEmail.getAddressRole();
    		personEmail.setPersonAddressKey(orgaPerson.getPersonNumber() +":"+addressRole.getAddressRoleKey() +":"+RandomStringUtils.randomNumeric(3));
    	}
    	// this is a dependent object of the person. So same record owner.
    	if(StringUtils.isBlank(personEmail.getRecordOwner())){
    		personEmail.setRecordOwner(orgaPerson.getRecordOwner());
    	}
        personEmailRepository.save(personEmail);
    }
    
    @Override
    public Page<PersonEmail> searchPersonEmail(OrgaPerson orgaPerson, 
    		EmailAddressRole addressRole,Integer page, Integer size)
    {
		PageRequest pageable = new PageRequest(page, size);
		if(orgaPerson!=null && addressRole==null){
			return personEmailRepository.findByOrgaPerson(orgaPerson, pageable);
		} else if(orgaPerson!=null && addressRole!=null){
			return personEmailRepository.findByOrgaPersonAndAddressRole(orgaPerson, addressRole, pageable);
		} else if(orgaPerson==null && addressRole!=null){
			return personEmailRepository.findByAddressRole(addressRole, pageable);
		} else {
			return personEmailRepository.findAll(pageable);
		}
    }

}
